﻿@{
    ViewData["Title"] = "FaceIndex";
    Layout = null;
}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>HTML5 GetUserMedia Demo</title>
    <link rel="stylesheet" href="~/Content/bootstrap-theme.css" media="all"/>
    <link rel="stylesheet" href="~/layui/css/layui.css">
    <link rel="stylesheet" href="~/layer/skin/layer.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
    <script type="text/javascript" src="~/html2canvas.js"></script>
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script  src="~/layui/layui.js"></script>
    <script  src="~/layer/layer.js"></script>
    <link rel="stylesheet" href="~/index.css">
    <style>
        .renlian {
            position: relative;
            height: 200px; width: 200px;
            margin: 255px 842px;
            background:url("../images/timg.png") no-repeat;
            background-size: 100% 100%;
        }
    </style>
</head>
<body>
<video style="width: 320px; display: none" autoplay="autoplay"></video>


<canvas id="backcanvas" width="280" height="270" style="position: fixed; top: 329px; left: 803px;"></canvas>
<div style="align-content: center; font-size: 50px; margin-left: 840px;margin-top: 100px">人脸识别</div>
<div class="renlian">
    <div class="box">
        <div class="line"></div>
        <div style="margin-left:1000px">
            <canvas id="canvas1" width="320" height="300" style="display: none"></canvas>
        </div>
        <div class="bottom"></div>
    </div>
    <input type="button" class="layui-btn layui-btn-radius layui-btn-normal" title="识别" value="识别" onclick="getPhoto();"/>
</div>



<script type="text/javascript">
    $(function() {
        getMedia();
    });

    var video = document.querySelector('video');
    var audio, audioType;

    var canvas1 = document.getElementById('canvas1');
    var context1 = canvas1.getContext('2d');

    var canvas2 = document.getElementById('backcanvas');
    var context2 = canvas2.getContext('2d');

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

    //开启摄像头
    function getMedia() {
        if (navigator.getUserMedia) {
            navigator.getUserMedia({
                    'video': {
                        'optional': [
                            {
                                'sourceId': "" //exArray[1] //0为前置摄像头，1为后置
                            }
                        ]
                    },
                    'audio': true
                },
                successFunc,
                errorFunc); //success是获取成功的回调函数
        } else {
            alert('Native device media streaming (getUserMedia) not supported in this browser.');
        }
    }

    function successFunc(stream) {
        mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
        //alert('Succeed to get media!');
        if (video.mozSrcObject !== undefined) {
            //Firefox中，video.mozSrcObject最初为null，而不是未定义的，我们可以靠这个来检测Firefox的支持
            video.mozSrcObject = stream;
        } else {

            try {
                video.src = window.URL.createObjectURL(stream);
            } catch (e) {
                video.srcObject = stream;
            }
            // video.src = window.URL && window.URL.createObjectURL(stream) || stream;
        }

        //video.play();

    }

    function errorFunc(e) {
        alert('Error！' + e);
    }

    // 将视频帧绘制到Canvas对象上,Canvas每60ms切换帧，形成肉眼视频效果
    function drawVideoAtCanvas(video, context) {
        window.setInterval(function() {
                context.drawImage(video, 0, 0, 370, 370);
            },
            20);
    }


    // vedio播放时触发，绘制vedio帧图像到canvas
    video.addEventListener('play',
        function() {
            drawVideoAtCanvas(video, context2);
        },
        false);

    //拍照
    function getPhoto() {
        context1.drawImage(video, 0, 0, 320, 320); //将video对象内指定的区域捕捉绘制到画布上指定的区域，实现拍照。

        //获取网页中的canvas对象
        var canvas = $('#canvas1')[0];
        //调用convertCanvasToImage函数将canvas转化为img形式
        var img = convertCanvasToImage(canvas);
        //将img插入容器
        //$('#img').append(img);

        var formData = new FormData();
        formData.append("image", img.src);
        //进行人脸识别相关操作
        $.ajax({
            url: '/Login/PostFaceDistinguish',
            type: 'post',
            cache: false, //每个ajax请求不接受缓存
            processData: false, //数据类型格式不变
            contentType: false, //进程
            data: formData,
            success: function(data) {
                var other = data.other;
                if (data.res == false) {
                    layer.msg("认证失败");
                    return;
                } else {
                    data = eval("(" + data.info + ")");
                    if (data.error_code == 0 && data.error_msg == "SUCCESS") {
                        layer.msg("认证成功");
                        CloseMedia();
                        location.href = "/Rbac/Default";
                    } else {
                        layer.msg("错误信息（具体信息可参照官网错误码）：" + data.error_msg);
                        return;
                    }
                }

            }
        });


    }

    //从 canvas 提取图片 image
    function convertCanvasToImage(canvas) {
        //新Image对象，可以理解为DOM
        var image = new Image();
        // canvas.toDataURL 返回的是一串Base64编码的URL
        // 指定格式 PNG
        image.src = canvas.toDataURL("image/png");
        return image;
    }

    //视频
    function getVedio() {
        drawVideoAtCanvas(video, context2);
    }

    //关闭摄像头
    function CloseMedia() {
        mediaStreamTrack && mediaStreamTrack.stop();
    }

    //获取guid
    function guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "" + S4() + "" + S4() + "" + S4() + "" + S4() + S4() + S4());
    }


    var interval, backCanvas, backCtx, img;
    var yFrontPosition = 0, step = 10, canvasWidth, canvasHeight;
    var canvasX = 0, canvasY = 0;

    window.onload = function() {
        initPageEle();
        drawImg();
        startrun();
    }

    function drawImg() {
        img = new Image();
        img.src = "/Content/face.png";
        //img.onload = loadImg;
    }

    function initPageEle() {
        backCanvas = document.getElementById("backcanvas");
        backCtx = backCanvas.getContext("2d");
        canvasWidth = backCanvas.width;
        canvasHeight = backCanvas.height;
        backCtx.fillStyle = 'rgba(255, 255, 255, 0)';
        backCtx.strokeStyle = "#24303a";
        backCtx.lineWidth = 2;
    }

    function loadImg() {
        backCtx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
        drawBackground();
    }

    function startrun() {
        interval = setInterval(draw, 100);
    }

    function draw() {
        drawFront();
    }

    function drawFront() {
        yFrontPosition = yFrontPosition + step;
     
    }

    function drawBackground() {
        backCtx.fillStyle = "#24303a";
        backCtx.globalAlpha = 0.4;
        backCtx.beginPath();
        backCtx.moveTo(canvasX, canvasY);
        backCtx.lineTo(canvasX + canvasWidth, canvasY);
        backCtx.lineTo(canvasX + canvasWidth, canvasY + canvasHeight);
        backCtx.lineTo(canvasX, canvasY + canvasHeight);
        backCtx.lineTo(canvasX, canvasY);
        backCtx.fill();
        backCtx.closePath();
        backCtx.stroke();
    }

    function stop() {
        clearInterval(interval);
    }


</script>
</body>
</html>